﻿using System;
using System.Collections.Generic;
using System.IO;
using ExtractItAll.Core;

namespace ExtractItAll.Extractors
{
  public abstract class BaseExtractor
  {
    protected BaseExtractor()
    {
      Canceled = false;
    }

    public bool Canceled { get; set; }
    public string Message { get; set; }

    public abstract string InfoText { get; }
    public abstract int Priority { get; }

    protected ArchiveItem Archive { get; set; }

    protected string DestinationDir
    {
      get
      {
        string subDir = GetCleanedSubDir(Path.GetFileNameWithoutExtension(Archive.FileName));

        if (Program.Settings.UseGlobalExtractPath && Directory.Exists(Program.Settings.ExtractPath))
        {
          return Program.Settings.ExtractToSubFolder
                   ?
                     Path.Combine(Program.Settings.ExtractPath, subDir)
                   :
                     Program.Settings.ExtractPath;
        }

        return Path.Combine(
          Path.GetDirectoryName(Archive.FileName),
          subDir);
      }
    }

    private static string GetCleanedSubDir(string archiveFilename)
    {
      if (archiveFilename == ".part1") return archiveFilename;
      if (archiveFilename == ".part01") return archiveFilename;
      if (archiveFilename == ".part001") return archiveFilename;
      if (archiveFilename == ".part0001") return archiveFilename;

      string ret = archiveFilename.Replace(".part1", String.Empty);
      ret = ret.Replace(".part01", String.Empty);
      ret = ret.Replace(".part001", String.Empty);
      ret = ret.Replace(".part0001", String.Empty);

      return ret;
    }


    public abstract bool Initialize(ArchiveItem archive);
    public abstract bool Extract(string password);
    public abstract void Close();

    public abstract bool IsArchiveFormatSupported(ArchiveFormat archiveFormat);
  }

  public class ExtractorComparer : IComparer<BaseExtractor>
  {
    #region IComparer<BaseExtractor> Member

    public int Compare(BaseExtractor x, BaseExtractor y)
    {
      return x.Priority.Equals(y.Priority) ? String.Compare(x.ToString(), y.ToString(), StringComparison.Ordinal) : x.Priority.CompareTo(y.Priority);
    }

    #endregion
  }
}